<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="params.username" placeholder="登陆账号" style="width: 300px;"class="filter-item" size="medium" clearable @keyup.enter.native="handleFilter" />
      <el-input v-model="params.enterName" placeholder="企业名称" style="width: 300px;margin-left: 10px"class="filter-item" size="medium" clearable @keyup.enter.native="handleFilter" v-if='userTypeCode != 1'/>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="medium" icon="el-icon-search"  @click="handleFilter">查询</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="medium" icon="el-icon-edit-outline" @click="handleCreate">创建</el-button>
    </div>
    <el-table :data="list" border v-loading="listLoading" style="width: 100%">
      <el-table-column type="index" align="center" label="序号" width="50"></el-table-column>
      <el-table-column prop="username" label="登录账号"></el-table-column>
      <el-table-column label="角色">
        <template slot-scope="{row}">
          {{ getRoleName(row.roles)}}
        </template>
      </el-table-column>
      <el-table-column prop="enterName" label="所属企业">
      </el-table-column>
      <el-table-column prop="code" label="员工编号">
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ userStatue(row.status)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template  slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button  size="mini" type="danger" @click="handleDelete(row,$index)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="params.page" :limit.sync="params.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class='enter-user-dialog'>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="margin: 0 40px;">
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="temp.username" v-bind:disabled="!(dialogStatus==='create')" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus==='create'">
          <el-input v-model="temp.password" show-password placeholder="请输入密码" clearable/>
        </el-form-item>
        <el-form-item label='所属企业' prop="enterId">
          <el-select v-model="temp.enterId" class="filter-item" placeholder="请选择" @change="enterChange" :disabled="userTypeCode != 1 && dialogStatus == 'update'" clearable style="width: 100%">
            <el-option v-for="item in enterList" :key="item.id" :label="item.enterName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label='用户角色' prop="roleIds">
          <el-select v-model="temp.roleIds" class="filter-item" placeholder="请选择"clearable @change="changeSelect"style="width: 100%">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name":value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination/index'
  import {
    createEnterUser,
    deleteEnterUser,
    getEnterUserList,
    updateEnterUser,
    getEnterRoleList,
    getEntertList
  } from '@/api/enter'
  export default {
    name: 'user',
    components: { Pagination },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        list: [],
        listLoading: false,
        roleList: [],
        enterList: [],
        total: 0,
        params:{
          username:'',
          enterName:'',
          page:1,
          limit:10,
        },
        dialogStatus: '',
        temp: {
          id: undefined,
          username: '',
          password: '',
          roleIds: '',
          enterId: '',
        },
        rules: {
          username: [{ required: true, message: '请填写用户名' }],
          password: [{ required: true, message: '请填写密码' }],
          enterId: [{ required: true, message: '请选择所属企业' }],
          roleIds: [{ required: true, message: '请选择角色' }]
        },
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '新建企业用户'
        },
        userTypeCode: '',
      }
    },
    created() {
      this.getList()

      getEntertList(params).then(response =>{
        this.enterList = response.data.records
      })
    },
    methods: {
      changeSelect(){
        this.$forceUpdate();
      },
      enterChange(){
        this.getRoleList()
      },
      userStatue(statue){
        return statue==1?"正常":"锁定"
      },
      getRoleName(roles){
        let roleName=''
        roles.forEach(route => {
          roleName+=route.roleName+","
        })
        roleName=roleName.substring(0,roleName.length-1)
        return roleName
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          username: '',
          password: '',
          roleIds: '',
          enterId: '',
        }
      },
      handleFilter() {
        this.params.page = 1
        this.getList()
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.getRoleList()
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            createEnterUser(this.temp).then(response=> {
              this.list.unshift(response.data)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) {
        let element = this.list[index]
        let data=[element.id];
        this.$confirm('确定删除该条数据？','提示', {
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteEnterUser(data).then(response =>{
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        }).catch(() => {

        });

      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.temp.roleIds=row.roles[0].roleId
        this.getRoleList()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateEnterUser(tempData).then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      getRoleList() {
        let enterId = this.temp.enterId
        const params={
          page:1,
          limit:20,
          enterId:enterId,
        }
        getEnterRoleList(params).then(response =>{
          this.roleList = response.data.records
          if(this.roleList.length == 0){
            this.temp.roleIds = ''
          }
        })
      },
      getList() {
        this.listLoading = true
        // this.params.channelCode = sessionStorage.getItem("channelCode") || '';
        getEnterUserList(this.params).then(response =>{
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      }
    }
  }
</script>

<style lang="scss">
  .enter-user-dialog .el-dialog{
    width: 30%
  }
  .enter-user-dialog .el-dialog__footer{
    text-align: center
  }
  .enter-user-dialog .el-dialog__body{
    padding: 30px 20px 0 20px
  }
</style>
